package com.whc.gulimall.order.web;

import com.whc.gulimall.order.service.OrderService;
import com.whc.gulimall.order.vo.OrderSubmitVo;
import com.whc.gulimall.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * @author angaoen
 */
@Controller(value = "webOrderController")
@Slf4j
public class OrderController {

    /**
     * 订单
     */
    @Resource
    private OrderService orderService;

    /**
     * 跳转页面
     *
     * @param page 页面
     * @return 跳转
     */
    @GetMapping("/{page}.html")
    public String redirectPage(@PathVariable("page") String page) {
        return page;
    }

    /**
     * 去购物车确认页
     *
     * @param model model
     * @return 购物车确认页
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) {
        try {
            model.addAttribute("orderConfirmVo", orderService.confirmOrder());
        } catch (ExecutionException | InterruptedException e) {
            return "redirect:http://gulimall.com";
        }
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String summitOrder(OrderSubmitVo submitVo, Model model) {
        try {
            SubmitOrderResponseVo responseVo = orderService.summitOrder(submitVo);
            if (responseVo.getCode() == 0) {
                model.addAttribute("submitOrderResponseVo", responseVo);
                return "pay";
            } else {
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (Exception e) {
            log.error("summitOrder(OrderSubmitVo submitVo, Model model)->{}", e.getMessage());
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
